package com.omesoft.hksnore.util.json;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.omesoft.hksnore.util.MySleepHandler;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfc;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.dao.MendaleSleepIfc;
import com.omesoft.hksnore.util.dao.MendaleSleepIfcImpl;
import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_Sleep;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_SleepDetail;
import com.omesoft.hksnore.util.thread.MyThread;
import com.omesoft.hksnore.util.web.WebServiceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class SyncUtil {

    private static int frequency = 0;
    private static String TAG = "SyncUtil";
    // private static Config config;
    private static String time;

    /**
     * 上传封面的队列<br>
     * 默认是mix_custom里的
     */
    private static Queue<Integer> mixIdQueue;

    public static void OfferMixId(int mix_id) {
        if (mixIdQueue == null)
            mixIdQueue = new LinkedList<Integer>();
        mixIdQueue.offer(mix_id);
    }

    public synchronized static void SyncSleepThread(final Context context, final Handler handler) {
        try {
            MyThread.startNewThread(new Runnable() {
                public void run() {
                    Log.v("testThread", "SyncSleepThread::Start");
                    // config = (Config) context.getApplicationContext();
                    HashMap<String, Object> param = new HashMap<String, Object>();

                    param.put("memberId", MySharedPreferencesUtil.getMemberId(context));
                    param.put("clientKey", MySharedPreferencesUtil.getCilenKey(context));
                    param.put("data", ToJsonUtil.allSleepInfo2String(context));


                    Log.v(TAG, "params::" + param.toString());
                    String resultStr = WebServiceUtils.callDotNetWS("Sync", param);
                    Log.v(TAG, "resultStr::" + resultStr);

                    if (resultStr != null) {
                        try {
                            frequency = 0; // 连接服务器次数归零
                            JSONObject temp = new JSONObject(resultStr);
                            int err_code = temp.getInt("err_code");
                            String msg = temp.getString("msg");
                            if (err_code == 0) {
                                JSONObject data = temp.getJSONObject("data");
                                JSONArray sleep = data.getJSONArray("sleep");
                                // JSONArray sleep_detail =
                                // data.getJSONArray("sleep_detail");
                                time = data.getString("timestamp");
                                // 插入数据
                                setSleep(context, sleep);
                                // getSleepDetail(context);
                                // setSleepDetail(context, sleep_detail);
                                // insertSleepData(context, sleep_detail,
                                // sleep);
                                // 保存服务器时间戳
                                if (MySharedPreferencesUtil.getBodyTime(context).equals("0")){
                                    sendMsg(handler,ReErrorCode.SYNC_SUCCEDFUL,"");
                                }
                                MySharedPreferencesUtil.setBodyTime(context, time);
                                // 保存本地时间戳
                                //MySharedPreferencesUtil.setLocalTime(context, MyDateUtil.getDateFormatToString(null));
                                MySharedPreferencesUtil.setLocalTime(context, MyDateUtil.getUpDateTime());


                                // QQ健康
                                // Log.v(TAG,
                                // "qqhealth::isbind::" +
                                // SharedPreferencesUtil.isQQHealthBind(context));
                                if (MySleepHandler.newInstance(context).getMonitorHandler() != null) {
                                    MySleepHandler.newInstance(context).getMonitorHandler().sendEmptyMessage(1);
                                }
                            } else {
                                sendMsg(handler,err_code,msg);
                            }

                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            System.gc();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (frequency < 5) {
                            // 防止连接服务器超时，当超时的时候请求重新连接数据库，当第5次连接不成功的时候断开连接，
                            // 避免因线程过多造成用户死机
                            SyncSleepThread(context, handler);
                            frequency++;
                        } else {
                            System.out.println("第5次连接不成功的时候断开连接");
                        }
                    }
                    Log.v("testThread", "SyncSleepThread::End");
                }

                ;
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置睡眠Medix_Pub_Sync_SleepDetail表数据
     *
     * @param context
     * @param sleepdetailstrs
     */
    public static void setSleepDetail(Context context, JSONArray sleepdetailstrs) {
//		Log.v("setSleepDetail", "data::" + sleepdetailstrs.toString());
        MendaleSleepIfc ifcImpl = new MendaleSleepIfcImpl(context);
        List<Medix_Pub_Sync_SleepDetail> dtos = new ArrayList<Medix_Pub_Sync_SleepDetail>();
        for (int i = 0; i < sleepdetailstrs.length(); i++) {
            Medix_Pub_Sync_SleepDetail dto = new Medix_Pub_Sync_SleepDetail();
            try {
                JSONObject object = sleepdetailstrs.getJSONObject(i);
                dto.setMemberID(MySharedPreferencesUtil.getMemberId(context));
                dto.setSleepID(object.getString("sleep_id"));
                dto.setSleepDetailID(object.getString("snore_detail_id"));
                dto.setSnoreDuration(object.getInt("snore_duration"));
                dto.setSnoreCount(object.getInt("snore_count"));
                dto.setSnoreStopCount(object.getInt("snore_stop_count"));
                dto.setActCount(object.getInt("act_count"));
                dto.setTurnCount(object.getInt("turn_count"));
                dto.setBreathRate(object.getInt("breath_rate"));
                dto.setRecordDate(object.getString("record_date"));
                dto.setUpdatedDate(object.getString("record_date"));
                dto.setCreatedDate(object.getString("record_date"));
                dto.setIsDeleted(object.getBoolean("is_deleted") == true ? 1 : 0);
                dtos.add(dto);
                // ifcImpl.insertOrUpdate(dto);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Log.e(TAG, "setSleepDetail: " + dtos.toString());
        ifcImpl.insertOrUpdate(dtos);
    }

    /**
     * 设置睡眠Medix_Pub_Sync_Sleep表数据
     *
     * @param context
     * @param sleepstrs
     */
    public static void setSleep(Context context, JSONArray sleepstrs) {

        MendaleSleepAllIfc allifcImpl = new MendaleSleepAllIfcImpl(context);
        List<Medix_Pub_Sync_Sleep> Sleeps = new ArrayList<Medix_Pub_Sync_Sleep>();
        for (int i = 0; i < sleepstrs.length(); i++) {
            Medix_Pub_Sync_Sleep dto = new Medix_Pub_Sync_Sleep();
            try {
                JSONObject object = sleepstrs.getJSONObject(i);
                // Log.v("SyncUtil::setSleep", "object::" + object.toString());
                dto.setMemberID(MySharedPreferencesUtil.getMemberId(context));
                dto.setSleepID(object.getString("sleep_id"));
                dto.setInBedTime(object.getInt("in_bed_time"));
                dto.setSleepTime(object.getInt("sleep_time"));
                dto.setDeepSleepTime(object.getInt("deep_sleep_time"));
                dto.setSleepScore(object.getInt("sleep_score"));
                dto.setRemark(object.getString("remark"));
                dto.setWakeupState(object.getInt("wakeup_state"));
                dto.setStartDate(object.getString("start_date"));
                dto.setEndDate(object.getString("end_date"));
                dto.setUpdatedDate(object.getString("end_date"));
                dto.setCreatedDate(object.getString("start_date"));
                dto.setIsDeleted(object.getBoolean("is_deleted") == false ? 0 : 1);
                dto.setQqHealth(object.getBoolean("qq_health") == false ? 0 : 1);
                dto.setDeviceName(object.getString("device_name"));
                dto.setSourceType(object.getInt("source_type"));
                dto.setTurnCount(object.getInt("turn_count"));// 翻身次数
                dto.setSnoreTime(object.getInt("snroe_duration"));
                dto.setSnoreCount(object.getInt("snore_count"));// 鼾声次数
                dto.setSnoreStopCount(object.getInt("snore_stop_count"));
                dto.setActCount(object.getInt("act_count"));
                dto.setBreathRate(object.getInt("breath_rate"));// 鼾声频率
                Sleeps.add(dto);
//				 ifcImpl.insertorupdate(dto);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        allifcImpl.insertorupdate(Sleeps);
    }

    public static void setSnoreData(Context context, JSONArray data) {
        if (data.length() > 0) {
            MendaleSleepIfcImpl Ifc = new MendaleSleepIfcImpl(context);
            List<Medix_Pub_Sync_SleepDetail> list = new ArrayList<Medix_Pub_Sync_SleepDetail>();

            for (int i = 0; i < data.length(); i++) {
                Medix_Pub_Sync_SleepDetail entity = new Medix_Pub_Sync_SleepDetail();
                try {
                    JSONObject object = data.getJSONObject(i);
                    entity.setMemberID(MySharedPreferencesUtil.getMemberId(context));
                    entity.setSleepID(object.getString("sleep_id"));
                    entity.setSleepDetailID(object.getString("snore_detail_id"));
                    entity.setSnoreDuration(object.getInt("snore_duration"));
                    entity.setSnoreCount(object.getInt("snore_count"));
                    entity.setSnoreStopCount(object.getInt("snore_stop_count"));
                    entity.setActCount(object.getInt("act_count"));
                    entity.setTurnCount(object.getInt("turn_count"));
                    entity.setBreathRate(object.getInt("breath_rate"));
                    entity.setRecordDate(object.getString("record_date"));
                    entity.setIsDeleted(object.getBoolean("is_deleted") == true ? 1 : 0);
                    //  Ifc.insert(entity);
                    list.add(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Ifc.insertOrUpdate(list);
        }
    }
    private static void sendMsg(Handler handler, int code, String msg) {
        Message message = Message.obtain();
        message.what = code;
        message.obj = msg;
        if (handler != null)
            handler.sendMessage(message);
    }
}